package com.swak.frame.common;

import java.util.Map;
import java.util.function.Function;

import org.slf4j.Logger;

import com.alibaba.fastjson.JSON;
import com.swak.frame.dto.base.SysRestCode;
import com.swak.frame.dto.request.RpcParamRequest;
import com.swak.frame.dto.response.Response;
import com.swak.frame.exception.JacksonException;
import com.swak.frame.logger.SwakLoggerFactory;
import com.swak.frame.util.JacksonUtils;


/**
 * export service base
 * ClassName: AbstractRpcService.java
 * 
 * @author colley.ma
 * @date 2021年3月17日 下午3:44:23
 */
public abstract class AbstractRpcService {
    protected Logger logger = SwakLoggerFactory.getLogger(this.getClass()); // 日志记录

    public byte[] fastJsonByte(Response response) {
        try {
            return JacksonUtils.writeValueAsBytes(response);
        } catch (JacksonException e) {
            logger.error("JsontoByte error", e);
        }
        return sysErrorSetting();
    }


    public byte[] callback(Map<String, Object> request,
        Function<RpcParamRequest, Response> mapper) {
        RpcParamRequest rpcParamRequest = null;
        try {
            rpcParamRequest = RpcParamRequest.getRpcParamRequest(request);
        } catch (JacksonException e) {
            logger.error("RpcParamRequest 解析参数失败！param:" + JSON.toJSONString(request), e);
            return invalidParamSetting();
        }
        return fastJsonByte(mapper.apply(rpcParamRequest));
    }

    /**
     * 系统错误
     *
     * @return
     */
    public byte[] sysErrorSetting() {
        Response response = new Response(SysRestCode.SYS_ERR);
        return JacksonUtils.writeValueAsBytes(response);
    }

    public byte[] invalidParamSetting() {
        Response response = new Response(SysRestCode.INVALID_PARAM);
        return JacksonUtils.writeValueAsBytes(response);
    }

    /**
     * 兜底方法
     *
     * @param params
     *
     * @return
     */
    public byte[] fallback(Map<String, Object> params) {
        return sysErrorSetting();
    }
}
